package com.soft.util.encrypt;

import java.util.*;

/**
 * 
 * 类名: SignCore ,系统签名和淘宝支付一样,参见淘宝的样例代码AlipayCore.java
 * 
 * @author slduan
 *
 */
public class SignCore {
	/**
	 * 除去数组中的空值和签名参数
	 * 
	 * @param sArray
	 *            签名参数组
	 * @return 去掉空值与签名参数后的新签名参数组
	 */
	public static Map<String, String> paramsFilter(Map<String, String> sArray) {
		Map<String, String> result = new HashMap<String, String>(16);
		if (sArray == null || sArray.size() <= 0) {
			return result;
		}
		for (String key : sArray.keySet()) {
			String value = sArray.get(key);
			if (value == null || "".equals(value) || "sign".equalsIgnoreCase(key)) {
				continue;
			}
			result.put(key, value);
		}
		return result;
	}

	/**
	 * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
	 * 
	 * @param params
	 *            需要排序并参与字符拼接的参数组
	 * @return 拼接后字符串
	 */
	public static String createLinkString(Map<String, String> params) {
		List<String> keys = new ArrayList<String>(paramsFilter(params).keySet());
		Collections.sort(keys);
		//String prestr = "";
		StringBuilder prestr=new StringBuilder("");
		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = params.get(key);
			if (i == keys.size() - 1) {
				prestr.append(key + "=" + value);
			} else {
				prestr.append(key + "=" + value+"&");
			}
		}
		return prestr.toString();
	}

	/**
	 * 把数组所有元素按照固定参数排序，以“参数=参数值”的模式用“&”字符拼接成字符串
	 * 
	 * @param params
	 *            需要参与字符拼接的参数组
	 * @return 拼接后字符串
	 */
	public static String createLinkStringNoSort(Map<String, String> params) {
		// 手机网站支付MD5签名固定参数排序，顺序参照文档说明
		StringBuilder gotoSignParams = new StringBuilder();
		gotoSignParams.append("service=" + params.get("service"));
		gotoSignParams.append("&v=" + params.get("v"));
		gotoSignParams.append("&sec_id=" + params.get("sec_id"));
		gotoSignParams.append("&notify_data=" + params.get("notify_data"));
		return gotoSignParams.toString();
	}

	public static String dataEncrypt(String data, String appsecret) {
		return Aes.encryptAes(data,appsecret);
	}
}
